package com.DongBing.controller;

import com.DongBing.common.utils.Res;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/alibaba/oss")
public class AlibabaController {

    private final OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    /**
     * 获取签名
     * @return res 签名
     */
    @GetMapping(value = "/getSecret")
    public Res<Map<String,String>> getSecret(){
        String host = "https://"+this.bucket+"."+this.endpoint;
        val dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dir = dateFormat.format(new Date());

        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            Map<String, String> respMap = new LinkedHashMap<>();
            respMap.put("accessid", this.accessId);
            respMap.put("policy", encodedPolicy);
            // 得到签名
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            return Res.success("操作成功",respMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传文件
     * @param file file
     * @return res
     */
    @PostMapping(value = "/upload")
    public Res<?> upload(MultipartFile file){
        try {
            val stream = file.getInputStream();
            val substring = Objects.requireNonNull(file.getOriginalFilename())
                    .substring(file.getOriginalFilename().lastIndexOf("."));
            val date = new Date();
            val dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            val time = dateFormat.format(date).toString();
            val fileName =time+"/"+UUID.randomUUID().toString()+ substring;
            ossClient.putObject(bucket,fileName,stream);
            val url = "https://"+bucket+"."+endpoint+"/"+fileName;
            return Res.success("上传成功",url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Res.error("上传失败");
    }

}
